<template>
  <div class="p-2">
    <el-row :gutter="20">
      <!-- 产品树 -->
      <el-col :lg="4" :xs="24" style="padding-right: 0;">
        <TreeLeft type="wms_product_tree" v-model:value="pd.queryParams.treeValue" @update:value="handleQuery" />
      </el-col>
      <el-col :lg="20" :xs="24">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
          :leave-active-class="proxy?.animate.searchAnimate.leave">
          <div class="search" v-show="pd.showSearch">
            <el-form :model="pd.queryParams" ref="queryFormRef" :inline="true" label-width="68px">
              <el-form-item label="产品编码" prop="sku">
                <el-input v-model="pd.queryParams.sku" placeholder="请输入产品编码" clearable style="width: 240px"
                  @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="产品名称" prop="name">
                <el-input v-model="pd.queryParams.name" placeholder="请输入产品名称" clearable style="width: 240px"
                  @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="产品规格" prop="specification">
                <el-input v-model="pd.queryParams.specification" placeholder="请输入产品规格" clearable style="width: 240px"
                  @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="更新时间" style="width: 308px">
                <el-date-picker v-model="dateRangeUpdateTime" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
                  range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                  :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </transition>
        <el-card shadow="never">
          <template #header>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['wms:product:add']">新增
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="success" plain icon="Edit" :disabled="pd.single" @click="handleUpdate()"
                  v-hasPermi="['wms:product:edit']">修改
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="danger" plain icon="Delete" :disabled="pd.multiple" @click="handleDelete()"
                  v-hasPermi="['wms:product:remove']">删除
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="warning" plain icon="Download" @click="handleExport"
                  v-hasPermi="['wms:product:export']">导出
                </el-button>
              </el-col>
              <right-toolbar v-model:showSearch="pd.showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
          </template>

          <el-table v-loading="pd.loading" :data="pd.productList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="产品id" align="center" prop="id" v-if="true" />
            <el-table-column label="产品编码" align="center" prop="sku" />
            <el-table-column label="产品名称" align="center" prop="name">
              <template #default="scope">
                <el-link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['wms:order:edit']">
                  {{ scope.row.name }}
                </el-link>
              </template>
            </el-table-column>
            <el-table-column label="产品规格" align="center" prop="specification" />
            <el-table-column label="包装单位" align="center" prop="packingUnit" />
            <el-table-column label="计量单位" align="center" prop="measureUnit" />
            <el-table-column label="包装数量" align="center" prop="packingQuantity" />
            <el-table-column label="销售价格" align="center" prop="price" />
            <el-table-column label="采购价格" align="center" prop="purchasePrice" />
            <el-table-column label="类别" align="center" prop="treeValue">
              <template #default="scope">
                <dictTag :options="wms_product_tree" :value="scope.row.treeValue" />
              </template>
            </el-table-column>
            <el-table-column label="产品属性" align="center" prop="attrValue" />
            <el-table-column label="产品状态" align="center" prop="status">
              <template #default="scope">
                <dict-tag :options="sys_status" :value="scope.row.status" />
              </template>
            </el-table-column>
            <el-table-column label="是否库存" align="center" prop="isStock">
              <template #default="scope">
                <dict-tag :options="sys_yes_no" :value="scope.row.isStock ? '1' : '0'" />
              </template>
            </el-table-column>
            <el-table-column label="可否销售" align="center" prop="isSales">
              <template #default="scope">
                <dict-tag :options="sys_yes_no" :value="scope.row.isSales ? '1' : '0'" />
              </template>
            </el-table-column>
            <el-table-column label="可否采购" align="center" prop="isPurchase">
              <template #default="scope">
                <dict-tag :options="sys_yes_no" :value="scope.row.isPurchase ? '1' : '0'" />
              </template>
            </el-table-column>
            <el-table-column label="可否生产" align="center" prop="isProduce">
              <template #default="scope">
                <dict-tag :options="sys_yes_no" :value="scope.row.isProduce ? '1' : '0'" />
              </template>
            </el-table-column>
            <el-table-column label="是否物料" align="center" prop="isMaterial">
              <template #default="scope">
                <dict-tag :options="sys_yes_no" :value="scope.row.isMaterial ? '1' : '0'" />
              </template>
            </el-table-column>
            <el-table-column label="委外加工" align="center" prop="isOutsource">
              <template #default="scope">
                <dict-tag :options="sys_yes_no" :value="scope.row.isOutsource ? '1' : '0'" />
              </template>
            </el-table-column>
            <el-table-column label="最低安全库存" align="center" prop="minStock" />
            <el-table-column label="最大安全库存" align="center" prop="maxStock" />
            <el-table-column label="备注" align="center" prop="remark" />
            <el-table-column fixed="left" label="操作" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                  v-hasPermi="['wms:product:edit']"> 修改
                </el-button>
                <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row.id)"
                  v-hasPermi="['wms:product:remove']">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="pd.total > 0" :total="pd.total" v-model:page="pd.queryParams.pageNum"
            v-model:limit="pd.queryParams.pageSize" @pagination="getList" />
        </el-card>
        <!-- 添加或修改物料产品对话框 -->

        <el-dialog :title="pd.dialog.title" v-model="pd.dialog.visible" width="1200px" append-to-body>
          <el-form ref="productFormRef" :model="pd.form" :rules="pd.rules" label-width="100px">
            <div style="margin-bottom: 15px">
              <el-radio-group v-model="radio">
                <el-radio-button label="1">产品属性</el-radio-button>
                <el-radio-button label="2">商城属性</el-radio-button>
              </el-radio-group>
            </div>
            <el-row :gutter="20">
                  <el-col :span="12">
                      <el-form-item label="sku码" prop="sku">
                        <el-input v-model="pd.form.sku" placeholder="请输入sku编码" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12" v-if =false>
                      <el-form-item label-width="80">
                        <el-switch v-model="autoGenFlag" active-color="#13ce66" active-text="自动生成"
                          @change="handleAutoGenChange(autoGenFlag)">
                        </el-switch>
                      </el-form-item>
                    </el-col>                  
                </el-row> 
            <el-row v-show="radio == '1'">              
              <el-col :span="8">
                <el-form-item label="产品名称" prop="name">
                  <el-input v-model="pd.form.name" placeholder="请输入产品名称" />
                </el-form-item>
                <el-form-item label="产品分类" prop="treeValue">
                  <TreeSelect dictType="wms_product_tree" v-model:dictValue="pd.form.treeValue" placeholder="请选择产品树" />
                </el-form-item>
                <el-form-item label="产品规格" prop="specification">
                  <el-input v-model="pd.form.specification" placeholder="请输入产品规格" />
                </el-form-item>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="销售价格" prop="price">
                      <el-input v-model="pd.form.price" placeholder="请输入销售价格" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="采购价格" prop="purchasePrice">
                      <el-input v-model="pd.form.purchasePrice" placeholder="请输入采购价格" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="最大安全库存" prop="maxStock">
                      <el-input v-model="pd.form.maxStock" placeholder="请输入最大库存" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="最低安全库存" prop="minStock">
                      <el-input v-model="pd.form.minStock" placeholder="请输入最低库存" />
                    </el-form-item>
                  </el-col>
                </el-row>
                
              </el-col>

              <el-col :span="8">
                <el-form-item label="计量单位" prop="measureUnit">
                  <el-input v-model="pd.form.measureUnit" placeholder="请输入计量单位" />
                </el-form-item>
                <el-form-item label="包装数量" prop="packingQuantity">
                  <el-input v-model="pd.form.packingQuantity" placeholder="请输入包装数量" />
                </el-form-item>
                <el-form-item label="包装单位" prop="packingUnit">
                  <el-input v-model="pd.form.packingUnit" placeholder="请输入包装单位" />
                </el-form-item>
                <el-form-item label="产品属性" prop="attrValue">
                  <el-input v-model="pd.form.attrValue" placeholder="请输入产品属性" />
                </el-form-item>                
                <el-form-item label="默认供应商" prop="partnerId">
                    <PartnerSearch :dataText="pd.form.partnerName" :params="{ isSupplier: true }"
                      @ok="searchSupplier1($event)" />
                  </el-form-item>
              </el-col>

     

              <el-col :span="8">
                <el-form-item label="产品状态" prop="status">
                  <el-radio-group v-model="pd.form.status">
                    <el-radio v-for="dict in sys_status" :label="dict.value">{{ dict.name }}</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="可否销售" prop="isSales">
                  <el-radio-group v-model="pd.form.isSales">
                    <el-radio v-for="dict in sys_yes_no" :label="dict.value == '1'">{{ dict.name }}</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="可否采购" prop="isPurchase">
                  <el-radio-group v-model="pd.form.isPurchase">
                    <el-radio v-for="dict in sys_yes_no" :label="dict.value == '1'">{{ dict.name }}</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="可否生产" prop="isProduce">
                  <el-radio-group v-model="pd.form.isProduce">
                    <el-radio v-for="dict in sys_yes_no" :label="dict.value == '1'">{{ dict.name }}</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="是否物料" prop="isMaterial">
                  <el-radio-group v-model="pd.form.isMaterial">
                    <el-radio v-for="dict in sys_yes_no" :label="dict.value == '1'">{{ dict.name }}</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>

              <el-row style="width:100%">              
                <el-col :span="16">
                  <el-form-item label="备注" prop="remark">
                    <el-input v-model="pd.form.remark" type="textarea" placeholder="请输入内容" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="委托加工" prop="isOutsource">
                    <el-radio-group v-model="pd.form.isOutsource">
                      <el-radio v-for="dict in sys_yes_no" :label="dict.value == '1'">{{ dict.name }}</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item label="产品图">
                <PictureUpload :limit=9 :show-list="true" :id-list="pd.productId" @ok="handleAccomplish" />
              </el-form-item>
            </el-row>

            <el-row v-show="radio == '2'">
              <el-form-item label="商城菜单" prop="mallMenuId">
                <el-tree-select v-model="pd.form.mallMenuId" :data="pd.menuList" :props="defaultProps" check-strictly
                  :render-after-expand="false" clearable />
              </el-form-item>
              <el-form-item label="描述" prop="desc">
                <el-input v-model="pd.form.desc" placeholder="请输入产品描述" />
              </el-form-item>
              <el-form-item label="旧价格" prop="oldPrice">
                <el-input v-model="pd.form.oldPrice" placeholder="请输入旧价格" />
              </el-form-item>
            </el-row>

          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button :loading="pd.buttonLoading" type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
            </div>
          </template>
        </el-dialog>

      </el-col>
    </el-row>
  </div>
</template>

<script setup name="Product" lang="ts">
import { addProduct, delProduct, getProduct, listProduct, ProductVO, updateProduct,Upload } from '@/views/wms/product/api';
import TreeLeft from '@/views/system/dict/treeLeft.vue';
import TreeSelect from '@/views/system/dict/treeSelect.vue';
import PartnerSearch from '@/views/hrp/partner/search.vue';
import PictureUpload from "@/views/system/minio/pictureUpload.vue";
import { listMenu, mallMenu } from "@/views/mall/api";
import { PartnerVO, getPartner } from "@/views/hrp/partner/api";
import {genCode} from '@/views/system/autocode/rule';

const autoGenFlag = ref(false);

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const {
  wms_product_tree,
  sys_status,
  sys_yes_no
} = toRefs<any>(proxy?.useDict('wms_product_tree', 'sys_status', 'sys_yes_no'));
const radio = ref('1')

const dateRangeUpdateTime = ref<[DateModelType, DateModelType]>(['', '']);

const queryFormRef = ref<ElFormInstance>();
const productFormRef = ref<ElFormInstance>();

const pd = reactive({
  productList: <ProductVO[]>([]),
  menuList: <mallMenu[]>([]),
  buttonLoading: false,
  loading: true,
  showSearch: true,
  ids: <Array<string | number>>([]),
  single: true,
  multiple: true,
  total: 0,
  pictureIds: <any>[],
  form: <ProductVO>{},
  productId: <any>[],
  queryParams: <ProductVO>{
    pageNum: 1,
    pageSize: 10,
    sku: undefined,
    name: undefined,
    specification: undefined,
    treeValue: '',
    isStock: undefined,
    params: {
      updateTime: undefined,
    }
  },
  rules: <ElFormRules>{
    sku: [{ required: true, message: "产品编码不能为空", trigger: "blur" }],
    name: [{ required: true, message: "产品名称不能为空", trigger: "blur" }],
    specification: [{ required: true, message: "产品规格不能为空", trigger: "blur" }],
    packingUnit: [{ required: true, message: "包装单位不能为空", trigger: "blur" }],
    measureUnit: [{ required: true, message: "计量单位不能为空", trigger: "blur" }],
    packingQuantity: [{ required: true, message: "包装数量不能为空", trigger: "blur" }],
    price: [{ required: true, message: "销售价格不能为空", trigger: "blur" }],
    purchasePrice: [{ required: true, message: "采购价格不能为空", trigger: "blur" }],
    treeValue: [{ required: true, message: "类别不能为空", trigger: "change" }],
    status: [{ required: true, message: "产品状态不能为空", trigger: "change" }],
    isStock: [{ required: true, message: "是否库存不能为空", trigger: "change" }],
    isSales: [{ required: true, message: "可否销售不能为空", trigger: "change" }]
  },
  dialog: <DialogOption>{
    visible: false,
    title: ''
  }
});

const defaultProps = {
  label: 'name',
  value: 'id',
  children: 'children',
}

/** 查询物料产品列表 */
async function getList() {
  pd.loading = true;
  pd.queryParams.params = {};
  proxy?.addDateRange(pd.queryParams, dateRangeUpdateTime.value, 'UpdateTime');
  const res = await listProduct(pd.queryParams);
  pd.productList = res.rows;
  pd.total = res.total;
  pd.loading = false;
}

/** 取消按钮 */
function cancel() {
  reset();
  pd.dialog.visible = false;
}

/** 表单重置 */
function reset() {
  // 设置默认值
  pd.form = <ProductVO>{};
  pd.form.isStock = true;
  pd.form.isSales = true;
  pd.form.status = '0';
  pd.form.isProduce = true;
  pd.form.isMaterial = true;
  pd.form.isOutsource = false;
  pd.form.isPurchase = true;
  pd.productId = [];
  pd.pictureIds = [];
  productFormRef.value?.resetFields();
  radio.value = '1';
}

/** 搜索按钮操作 */
function handleQuery() {
  pd.queryParams.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRangeUpdateTime.value = ['', ''];
  pd.queryParams.treeValue = '';
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection: ProductVO[]) {
  pd.ids = selection.map(item => <number>item.id);
  pd.single = selection.length != 1;
  pd.multiple = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  pd.dialog.title = "添加物料产品";
  pd.form.status = "0";
  pd.form.isSales = true;
  pd.dialog.visible = true;
}

/** 修改按钮操作 */
async function handleUpdate(row?: ProductVO) {
  reset();
  const _id = row?.id || pd.ids[0]
  const res = await getProduct(_id);
  Object.assign(pd.form, res.data);
  pd.productId[0] = res.data.id;
  // 获取供应商详细信息
  if (pd.form.partnerId) {
    try {
      const partnerRes = await getPartner(pd.form.partnerId);
      pd.form.partnerName = partnerRes.data.name; // 假设返回的数据中包含 name 字段
    } catch (error) {
      console.error('获取供应商信息失败:', error);
      proxy?.$modal.msgError('获取供应商信息失败');
    }
  }
  // pd.form.partnerName = 'asdf';
  pd.dialog.visible = true;
  pd.dialog.title = "修改物料产品";
}

/** 提交按钮 */
function submitForm() {
  let index = 0
  pd.form.productOss = []
  pd.pictureIds.forEach((item: any) => {
    pd.form.productOss!.push(
      {
        productId: pd.form.id,
        ossId: item,
        sort: index
      }
    )
    index++
  })
  productFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      pd.buttonLoading = true;
      if (pd.form.id) {
        await updateProduct(pd.form).finally(() => pd.buttonLoading = false);
      } else {
        await addProduct(pd.form).finally(() => pd.buttonLoading = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      pd.dialog.visible = false;
      await getList();
    }
  });
}

//更新产品图片
function handleAccomplish(list: any) {
  pd.pictureIds = [];
  list.forEach((element: any) => {
    pd.pictureIds.push(element.ossId)
  });
}

/** 删除按钮操作 */
async function handleDelete(row?: ProductVO) {
  const _ids = row?.id || pd.ids;
  await proxy?.$modal.confirm('是否确认删除服务产品编号为"' + _ids + '"的数据项？').finally(() => pd.loading = false);
  await delProduct(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
function handleExport() {
  proxy?.download('wms/product/export', {
    ...pd.queryParams
  }, `product_${new Date().getTime()}.xlsx`)
}

function searchSupplier1(pVo: PartnerVO[]) {
  pVo.forEach((v, i, a) => {
    pd.form.partnerId = v.id;
    pd.form.partnerName = v.name;
    return;
  });
}
function handleAutoGenChange(autoGenFlag:boolean) {
  if(autoGenFlag){    
        genCode('ITEM_CODE').then(response =>{
          pd.form.sku = response.toString();
        });
      }else{
        pd.form.sku = '';
      }

}


/** 查询菜单列表 */
async function getMenuList() {
  pd.queryParams.params = {};
  const res = await listMenu();
  pd.menuList = res.rows;
  pd.menuList = proxy?.handleTree<mallMenu>(res.rows, "id", "parentId", "children") as mallMenu[];
}

onMounted(() => {
  pd.queryParams.isStock = true;
  pd.form.isStock = true;
  getList();
  getMenuList();
});
</script>
